﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace com.tanlingyun.helper
{
    /// <summary>
    /// 网页网络相关帮助类
    /// </summary>
    public class WebHelper
    {
        public static string GetIP(HttpRequestBase req = null)
        {
            string ip = string.Empty;
            if(req!=null)
            {

                if (!string.IsNullOrWhiteSpace(req.ServerVariables["HTTP_VIA"]))
                    ip = Convert.ToString(req.ServerVariables["HTTP_X_FORWARDED_FOR"]).Split(',')[0];
                if (string.IsNullOrWhiteSpace(ip))
                    ip = Convert.ToString(req.ServerVariables["REMOTE_ADDR"]);
            }else
            {
                if (!string.IsNullOrWhiteSpace(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
                ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]).Split(',')[0];
                if (string.IsNullOrWhiteSpace(ip))
                    ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
            }
            if (string.IsNullOrWhiteSpace(ip)) ip = "::-1";
            return ip;
        }

        public static T GetEntity<T>(FormCollection collection)
        {
            Type entityType = typeof(T);
            try
            {
                T entity = (T)Assembly.Load(entityType.Assembly.FullName).CreateInstance(entityType.FullName);
                foreach (var p in entityType.GetProperties())
                {
                    try
                    {
                        if (typeof(System.Enum).IsAssignableFrom(p.PropertyType))
                        {
                            p.SetValue(entity, Enum.Parse(p.PropertyType, collection[p.Name]));
                        }
                        else
                        {
                            p.SetValue(entity, Convert.ChangeType(collection[p.Name], p.PropertyType));
                        }
                    }
                    catch(Exception)
                    {
                        continue;
                    }
                }
                return entity;
            }
            catch(Exception ex)
            {
                return default(T);
            }
        }

        public static bool IsUrl(string url)
        {
            try
            {
                Uri uri = new Uri(url);
                return true;
            }
            catch(UriFormatException)
            {
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
        
        /// <summary>
        /// 获取请求参数
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string,object> GetCommonRequestParameters()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            HttpContext httpContext = HttpContext.Current;
            if (httpContext != null)
            {
                HttpRequest request =  httpContext.Request;
                if (request != null)
                {
                    string contentType = httpContext.Request.Headers["Content-Type"];
                    if (!string.IsNullOrWhiteSpace(contentType))
                    {
                        dict.Add("Content-Type", contentType);
                    }
                    dict.Add("HttpMethod", request.HttpMethod);
                    dict.Add("url", request.Url);
                    if (request.HttpMethod.ToLower().Equals("post") && request.InputStream != null && request.InputStream.Length > 0)
                    {
                        if(request.InputStream.CanRead)
                        {
                            byte[] data = new byte[request.InputStream.Length];
                            if(request.InputStream.Position!=0)
                            {
                                if (request.InputStream.CanSeek)
                                    request.InputStream.Position = 0;
                            }
                            request.InputStream.Read(data, 0, data.Length);
                            dict.Add("data", System.Text.Encoding.UTF8.GetString(data));
                        }
                    }else if(request.HttpMethod.ToLower().Equals("get"))
                    {
                        dict.Add("data",request.QueryString);
                    }
                    if(!string.IsNullOrWhiteSpace(request.UserAgent))
                    {
                        dict.Add("UserAgent", request.UserAgent);
                    }

                    object controller = httpContext.Request.RequestContext.RouteData.Values["controller"];
                    object action = httpContext.Request.RequestContext.RouteData.Values["action"];
                    dict.Add("controller", controller == null ? "" : controller.ToString());
                    dict.Add("action", action == null ? "" : action.ToString());
                    
                }
            }
            
            return dict;
        }

        public static string GetTitle(string html)
        {
            string title = "";
            Regex reg = new Regex(@"(?m)<title[^>]*>(?<title>(?:\w|\W)*?)</title[^>]*>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            Match mc = reg.Match(html);
            if (mc.Success)
                title = mc.Groups["title"].Value.Trim();
            return title;
        }

        public static string GetCharset(string html)
        {
            string charset = "";
            Regex reg = new Regex("^([\\s\\S]*)(<meta\\s+http-equiv=\"Content - Type\"\\s+content=\"text/html;\\s*charset=)(\\w+)(\">[\\s\\S]*)$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            Match mc = reg.Match(html);
            if (mc.Success)
                charset = mc.Groups["title"].Value.Trim();
            return charset;
        }
    }
}
